//
//  MyHealthMoodViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-19.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyHealthMoodViewController.h"
#import "MyHealthLogModel.h"
#import "UserId.h"
#import "XHImageViewer.h"
@interface MyHealthMoodViewController ()<XHImageViewerDelegate>
{
    NSMutableArray *imageArrays;
    NSInteger picCount;
}
/**
 *  心情的描述
 */
@property (strong, nonatomic) IBOutlet UILabel *descriptionLabel;
/**
 * 呈现数据的view
 */
@property (strong, nonatomic) IBOutlet UIView *backgroundView;
/**
 *  图片的显示
 */
@property (strong, nonatomic) IBOutlet UIImageView *logImageView;
/**
 *  固定的内容<健康心情>
 */
@property (strong, nonatomic) IBOutlet UILabel *labelWithInfl;
/**
 *  删除按钮
 */
@property (strong, nonatomic) IBOutlet UIButton *deleteButton;
/**
 *  日期
 */
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;
/**
 *  删除的数据的字典
 */
@property (nonatomic, strong) NSMutableDictionary *deleteDic;
@property (nonatomic, strong) MyHealthLogModel *healthObjc;

// 存放图片
@property (nonatomic, strong) UIImageView *imageViews;
@end

@implementation MyHealthMoodViewController

//- (UIImageView *)imageViews{
//    if (_imageViews == nil) {
//        _imageViews = [[UIImageView alloc] init];
//    }
//    return _imageViews;
//}

- (MyHealthLogModel *)healthObjc{
    if (_healthObjc == nil) {
        _healthObjc = [[MyHealthLogModel alloc] init];
    }
    return _healthObjc;
}

- (NSMutableDictionary *)deleteDic{
    if (_deleteDic == nil) {
        self.deleteDic = [NSMutableDictionary dictionary];
    }
    return _deleteDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    MyNSLog("%@", self.currentObjcDataLine);
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.backgroundView.layer.masksToBounds = YES;
    self.backgroundView.layer.cornerRadius = 2;
    self.backgroundView.layer.borderWidth = 0.5;
    self.backgroundView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.logImageView.layer.masksToBounds = YES;
    self.logImageView.layer.cornerRadius = 3;
    self.logImageView.userInteractionEnabled = YES;
    [self.logImageView setImageWithURL:[NSURL URLWithString:self.picArray[0]]];
    // Do any additional setup after loading the view from its nib.
    
     self.view.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self _parseHealthDataSource:kBaseURL];
    self.navigationItem.title = @"我的健康日志";

    
    imageArrays = [NSMutableArray array];
    
//    for (NSString *str in self.picArray) {
//        UIImageView *picImageView = [[UIImageView alloc] init];
//        [picImageView setImageWithURL:[NSURL URLWithString:str]];
//        [imageArrays addObject:picImageView];
//    }
    [self setNaviBarAttribute];
    [self setViewFrame];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightButton.frame = CGRectMake(0, 0, 23, 23);
//    [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
//    [rightButton addTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}
/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

///**
// *  完成(返回并传值)
// */
//- (void)handleRightButtonAction{
//    
//}

- (void)tapHandleAction:(UIGestureRecognizer *)sender{
    
    MyNSLog("===");
    CGPoint location=[sender locationInView:self.view];
    
    UIView *hitView=[self.view hitTest:location withEvent:nil];
    picCount = hitView.tag;
    XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
    imageViewer.delegate = self;
    [imageViewer showWithImageViews:imageArrays selectedView:(UIImageView *)[self.view viewWithTag:picCount]];
}



/**
 *  删除按钮执行方法
 */
- (IBAction)deleteButtonAction:(id)sender {
    [self deleteDataSource];
}

//  获取自适应label的高度 并让试图适应本高度
- (CGFloat)adaptiveLabelHeight:(NSString *)text wihtWight:(CGFloat)wight{
    UILabel *alablel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, wight, 25)];
    alablel.text = text;
    alablel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
    CGSize size = CGSizeMake(wight, 20000000);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13],NSFontAttributeName, nil];
    CGSize redSize = [alablel.text boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return redSize.height;
}

/**
 *  设置适应心情后的各个控件的frame 
 */
- (void)setViewFrame{
    
    self.descriptionLabel.text = self.contentStr;
    self.descriptionLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
    
   CGFloat heights = [self adaptiveLabelHeight:self.descriptionLabel.text wihtWight:self.backgroundView.frame.size.width - 30];
    self.descriptionLabel.frame = CGRectMake(15, 5, self.backgroundView.frame.size.width - 30, heights);
    if (kScreenWidth == 414) {
        self.logImageView.frame = CGRectMake(15, heights + 25, 66, 66);
    }else{
        self.logImageView.frame = CGRectMake(15, heights + 25, 55, 55);
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandleAction:)];
    tap.numberOfTapsRequired = 1;
    [self.logImageView addGestureRecognizer:tap];
    
    self.logImageView.tag = 100;
    if (self.picArray.count >= 1) {
        [self.logImageView setImageWithURL:[NSURL URLWithString:self.picArray[0]]];
        [imageArrays addObject:self.logImageView];
        for (NSInteger i = 1; i < self.picArray.count; i++) {
            if (kScreenWidth == 414) {
                self.imageViews = [[UIImageView alloc] initWithFrame:CGRectMake(15 + 106 * i, heights + 25, 66, 66)];
            }else{
                self.imageViews = [[UIImageView alloc] initWithFrame:CGRectMake(15 + 78 * i, heights + 25, 55, 55)];
            }
            UITapGestureRecognizer *taps = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandleAction:)];
            self.imageViews.userInteractionEnabled = YES;
            taps.numberOfTapsRequired = 1;
            self.imageViews.layer.masksToBounds = YES;
            self.imageViews.layer.cornerRadius = 3;

            [self.imageViews addGestureRecognizer:taps];
            [self.backgroundView addSubview:self.imageViews];
            [self.imageViews setImageWithURL:[NSURL URLWithString:self.picArray[i]] placeholderImage:[UIImage imageNamed:@"公用_默认图片"]];
            self.imageViews.tag = 100 + i;
            [imageArrays addObject:self.imageViews];
        }

    }
    if (kScreenWidth == 414) {
        self.backgroundView.frame = CGRectMake(0, 10, self.view.frame.size.width, heights + 82 + 8 + 15);
        self.labelWithInfl.frame = CGRectMake(15, heights + 82 + 16 + 8 + 15, 60, 16);
        self.labelWithInfl.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
        self.deleteButton.frame = CGRectMake(self.view.frame.size.width - 118 - 10, heights + 82 + 16 + 8 + 15, 30, 16);
        self.deleteButton.titleLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
        self.timeLabel.frame = CGRectMake(self.view.frame.size.width - 16 - 58 - 10, heights + 82 + 14 + 12 + 15, 65, 12);
        self.timeLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_TIME];
    }else{
        self.backgroundView.frame = CGRectMake(0, 10, self.view.frame.size.width, heights + 67 + 8 + 15);
        self.labelWithInfl.frame = CGRectMake(15, heights + 67 + 16 + 8 + 15, 60, 13);
        self.deleteButton.frame = CGRectMake(self.view.frame.size.width - 118, heights + 67 + 16 + 8 + 15, 30, 13);
        self.timeLabel.frame = CGRectMake(self.view.frame.size.width - 16 - 58 , heights + 67 + 14 + 12 + 15, 59, 10);
    }
    self.timeLabel.text = [self setNewTime];
}


#pragma mark - 删除数据 -
- (void)deleteDataSource{
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/logdel/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [self.deleteDic setValue:kPlatform forKey:@"platform"];
    [self.deleteDic setValue:kVersion forKey:@"version"];
    [self.deleteDic setValue:@"1" forKey:@"type"];
    [self.deleteDic setValue:self.healthObjc.dateline forKey:@"dateline"];
    [self.deleteDic setValue:self.healthObjc.logid forKey:@"logid"];
    MyNSLog("%@", self.deleteDic);
    [manager POST:postURL parameters:self.deleteDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
           [self showCustomHudSingleLine:@"删除失败"];
        }else{
            MyNSLog("========%@========", [responseObject objectForKey:@"msg"]);
            
            [self.deleteButton removeTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self showCustomHudSingleLine:@"删除成功"];
            [self performSelector:@selector(waitPopAction) withObject:nil afterDelay:0.6];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];
}

- (void)waitPopAction{
    
    NSUserDefaults *currentTimeMood = [NSUserDefaults standardUserDefaults];
    [currentTimeMood setObject:@"" forKey:@"currentTimeMood"];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网路数据请求 -
- (void)_parseHealthDataSource:(NSString *)urlString{
    [self showActionView];
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/log/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:kPlatform forKey:@"platform"];
    [parameters setValue:kVersion forKey:@"version"];
    [parameters setValue:@"1" forKey:@"type"];
    [parameters setValue:@"1" forKey:@"page"];
    [parameters setValue:[UserId shareUid].uidStr forKey:@"uid"];
    [parameters setValue:self.currentObjcDataLine forKey:@"daytime"];
    if ([self.currentObjcDataLine isEqualToString:@"今天"]) {
        [parameters setValue:[self setNewTime] forKey:@"daytime"];
    }else{
        [parameters setValue:self.currentObjcDataLine forKey:@"daytime"];
    }
    MyNSLog("%@", parameters);
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        NSString *statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            
        }else{
            NSMutableArray *array = [responseObject objectForKey:@"data"];
            MyNSLog("数组 = %@", array);
            for (NSInteger i = 0; i < array.count; i++) {
                [self.healthObjc setValuesForKeysWithDictionary:[array objectAtIndex:i]];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];
}



#pragma mark - 获取当前的时间 -

- (NSString *)setNewTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[formatter stringFromDate: [NSDate date]];
    return locationString;
    
}
//- (NSString *)setNewTime{
//    NSDate *now = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
//    int year = [dateComponent year];
//    int month = [dateComponent month];
//    int day = [dateComponent day];
//    NSString *times = [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
//    return times;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
